package com.xhtt.modules.app.controller.sys;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.utils.Constant;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.R;
import com.xhtt.common.validator.Assert;
import com.xhtt.common.validator.ValidatorUtils;
import com.xhtt.modules.app.annotation.Login;
import com.xhtt.modules.app.annotation.LoginUser;
import com.xhtt.modules.cfg.entity.CfgComprod;
import com.xhtt.modules.cfg.entity.CfgIsland;
import com.xhtt.modules.cfg.service.CfgComprodService;
import com.xhtt.modules.cfg.service.CfgIslandService;
import com.xhtt.modules.sys.controller.AbstractController;
import com.xhtt.modules.sys.entity.SysDeptEntity;
import com.xhtt.modules.sys.entity.SysUserCertEntity;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.sys.entity.SysUserProduct;
import com.xhtt.modules.sys.form.PasswordForm;
import com.xhtt.modules.sys.model.AddUserToTempTeamModel;
import com.xhtt.modules.sys.model.UserCertModel;
import com.xhtt.modules.sys.service.SysUserProductService;
import com.xhtt.modules.sys.service.SysUserService;
import com.xhtt.modules.task.model.car.CarTaskUserStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统用户
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月31日 上午10:40:10
 */
@Api(value = "系统管理-系统用户", tags = "系统管理-系统用户")
@RestController
@RequestMapping("app/sys/user")
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserProductService sysUserProductService;
    @Autowired
    private CfgComprodService cfgComprodService;
    @Autowired
    private CfgIslandService islandService;

    /**
     * 用户列表
     */
    @ApiOperation("用户列表(web/app)")
    @GetMapping("/list")
    @Login
    public R list(@RequestParam Map<String, Object> params, @ApiIgnore @LoginUser SysUserEntity user) {
        //只有超级管理员，才能查看所有管理员列表
//        if (user.getUserId() != Constant.SUPER_ADMIN) {
//            params.put("roleIds", user.getRoleIdList());// 用户所在机构或政府或企业的所有roleId
//        }
        PageUtils page = sysUserService.queryUserPage(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 作业人员列表
     */
    @ApiOperation("数据字典-作业人员列表(web/app)")
    @GetMapping("/workUserlist")
    @Login
    public R workUserlist(@RequestParam Map<String, Object> params) {
        PageUtils page = sysUserService.queryWorkUserPage(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 获取作业人员的证书
     */
    @ApiOperation("获取作业人员的证书(web/app)")
    @GetMapping("/workUserCerts")
    @Login
    public R workUserCerts(@RequestParam Integer userId) {
        List<SysUserCertEntity> list = sysUserService.workUserCerts(userId);
        return R.ok().put(Constant.DATA, list);
    }

    /**
     * 编辑作业人员的证书
     */
    @ApiOperation("编辑作业人员的证书(web)")
    @PostMapping("/updateWorkUserCerts")
    @Login
    public R updateWorkUserCerts(@RequestBody UserCertModel userCertModel) {
        ValidatorUtils.validateEntity(userCertModel);
        sysUserService.updateWorkUserCerts(userCertModel);
        return R.ok();
    }

    /**
     * 根据roleId获取用户列表
     */
//    @ApiOperation("根据roleId获取用户列表")
//    @GetMapping("/listByRole")
//    @Login
//    public R listByRole(@RequestParam Map<String, Object> params) {
//        Long roleId = Long.valueOf(params.get("roleId").toString());
//        params.put("roleIds", sysRoleService.getAllChildId(roleId));
//        PageUtils page = sysUserService.listByRole(params);
//        return R.ok().put(Constant.DATA, page);
//    }

    /**
     * 获取登录的用户信息
     */
    @ApiOperation("获取登录的用户信息(web/app)")
    @GetMapping("/loginUserInfo")
    @Login
    public R loginUserInfo(@ApiIgnore @LoginUser SysUserEntity user) {
        return R.ok().put("user", user);
    }

    /**
     * 修改登录用户密码
     */
    @ApiOperation("修改登录用户密码(web/app)")
    @PostMapping("/password")
    @Login
    public R password(@RequestBody PasswordForm form, @ApiIgnore @LoginUser SysUserEntity user) {
        Assert.isBlank(form.getNewPassword(), "新密码不为能空");

        //sha256加密
        String password = new Sha256Hash(form.getPassword(), user.getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), user.getSalt()).toHex();

        //更新密码
        boolean flag = sysUserService.updatePassword(user.getUserId(), password, newPassword);
        if (!flag) {
            return R.error("原密码不正确");
        }

        return R.ok();
    }

    /**
     * 用户信息
     */
    @ApiOperation("用户信息(web/app)")
    @GetMapping("/info/{userId}")
    @Login
    public R info(@PathVariable("userId") Long userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        PageUtils page = sysUserService.queryUserPage(params);
        if (page.getTotalCount() < 1) {
            throw new RRException("对象不存在");
        }
        SysUserEntity user = (SysUserEntity) page.getList().get(0);
        if (StringUtils.isNotEmpty(user.getDeptId())) {
            List<Long> deptIds = new ArrayList<>();
            deptIds.add(Long.valueOf(user.getDeptId()));
            user.setDeptIdList(deptIds);
        }
        List<SysUserProduct> ps = sysUserProductService.list(new LambdaQueryWrapper<SysUserProduct>().eq(SysUserProduct::getUserId, userId).select(SysUserProduct::getProductId, SysUserProduct::getId));
        if (ps.size() > 0) {
            List<Integer> pIds = ps.stream().map(SysUserProduct::getProductId).collect(Collectors.toList());
            if (pIds.size() > 0) {
                List<CfgComprod> comprods = cfgComprodService.listByIds(pIds).stream().collect(Collectors.toList());
                user.setOperComprods(comprods);

            }
        }


        return R.ok().put(Constant.DATA, user);
    }

    /**
     * 保存用户
     */
    @ApiOperation("保存用户(web)")
    @PostMapping("/save")
    @Login
    public R save(@RequestBody SysUserEntity addUser) {
        ValidatorUtils.validateEntity(addUser);
        sysUserService.saveUser(addUser);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户(web/app)")
    @PostMapping("/update")
    @Login
    public R update(@RequestBody SysUserEntity user) {
        if (null == user.getUserId()) {
            throw new RRException("请求参数有误");
        }
        ValidatorUtils.validateEntity(user);

        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 修改用户状态
     */
    @ApiOperation("修改用户状态(web)")
    @PostMapping("/status")
    @Login
    public R status(@RequestBody Map<String, Object> map) {
        if (null == map.get("userIds") || null == map.get("status")) {
            throw new RRException("请求参数有误");
        }
        List<Integer> userIds = (List<Integer>) map.get("userIds");
        SysUserEntity nu = new SysUserEntity();
        nu.setStatus((Integer) map.get("status"));
        sysUserService.update(nu, new QueryWrapper<SysUserEntity>().in(SysUserEntity.USERID, userIds));
        return R.ok();
    }

    /**
     * 重置密码为工号
     */
    @ApiOperation("重置密码为工号(web/app)")
    @PostMapping("/rePassword")
    @Login
    public R rePassword(@RequestBody Integer[] userIds) {
        List<SysUserEntity> users = sysUserService.listByIds(Arrays.asList(userIds)).stream().collect(Collectors.toList());
        List<SysUserEntity> newUsers = new ArrayList<>();
        SysUserEntity newUser;
        for (SysUserEntity user : users) {
            newUser = new SysUserEntity();
            newUser.setUserId(user.getUserId());
            newUser.setPassword(new Sha256Hash(user.getWorkNo(), user.getSalt()).toHex());
            newUsers.add(newUser);
        }
        if (CollectionUtils.isNotEmpty(newUsers)) {
            sysUserService.updateBatchById(newUsers);
        }
        return R.ok();
    }

    /**
     * 修改用户的角色（部门）
     */
//    @ApiOperation("修改用户的角色（部门）")
//    @PostMapping("/updateUserDept")
//    @Login
//    public R updateUserDept(@RequestBody UpdateUserDeptModel model) {
//        if (CollectionUtils.isEmpty(model.getUserIdList())) {
//            throw new RRException("请求参数有误");
//        }
//        sysUserDeptService.saveOrUpdate(model.getUserIdList(), model.getDeptIdList());
//
//        return R.ok();
//    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户(web)")
    @PostMapping("/delete")
    @Login
    public R delete(@RequestBody Long[] userIds, @ApiIgnore @LoginUser SysUserEntity user) {
        if (ArrayUtils.contains(userIds, Constant.SUPER_ADMIN)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, user.getUserId())) {
            return R.error("当前用户不能删除");
        }

        sysUserService.deleteBatch(userIds);

        return R.ok();
    }

    /**
     * 获取部门-用户数据
     */
    @ApiOperation("获取部门-用户数据(app)")
    @GetMapping("/deptUser")
    @Login
    public R deptUser() {
        List<SysDeptEntity> list = sysUserService.deptUser();
        return R.ok().put(Constant.DATA, list);
    }


    //-----------APP神奇的功能（坑爹的功能）------------

    /**
     * 获取装车组里面的人员
     */
    @ApiOperation("获取装车组里面的人员(app)")
    @GetMapping("/zhuangcheTeamUser")
    @Login
    public R zhuangcheTeamUser(@RequestParam(required = false) Integer loadAreaType, @ApiIgnore @LoginUser SysUserEntity user) {
        List<CarTaskUserStatus> teamUser = sysUserService.zhuangcheTeamUser(loadAreaType, user);
        String loadAreaName = "";
        if (null != loadAreaType) {
            CfgIsland island = islandService.getOne(new LambdaQueryWrapper<CfgIsland>().eq(CfgIsland::getLoadAreaType, loadAreaType));
            if (null != island) {
                loadAreaName = island.getLoadAreaName();
            }
        }
        return R.ok().put(Constant.DATA, teamUser).put("loadAreaName", loadAreaName);
    }

    /**
     * 获取当前用户所在部门里面装车组里面的临时组人员
     */
    @ApiOperation("获取当前用户所在部门里面装车组里面的临时组人员(app)")
    @GetMapping("/zhuangcheTempTeamUser")
    @Login
    public R zhuangcheTempTeamUser(@RequestParam Integer loadAreaType, @ApiIgnore @LoginUser SysUserEntity user) {
        List<CarTaskUserStatus> teamUser = sysUserService.zhuangcheTempTeamUser(loadAreaType, user);
        String loadAreaName = "";
        if (null != loadAreaType) {
            CfgIsland island = islandService.getOne(new LambdaQueryWrapper<CfgIsland>().eq(CfgIsland::getLoadAreaType, loadAreaType));
            if (null != island) {
                loadAreaName = island.getLoadAreaName();
            }
        }
        return R.ok().put(Constant.DATA, teamUser).put("loadAreaName", loadAreaName);
    }

    /**
     * 添加人员进临时组
     */
    @ApiOperation("添加人员进临时组(app)")
    @PostMapping("/addUserToTempTeam")
    @Login
    public R addUserToTempTeam(@ApiIgnore @LoginUser SysUserEntity user, @RequestBody AddUserToTempTeamModel model) {
        if (null == model || null == model.getLoadAreaType()) {
            throw new RRException("参数有误");
        }
        sysUserService.addUserToTempTeam(user, model);
        return R.ok();
    }

    /**
     * 临时组移除人员
     */
    @ApiOperation("临时组移除人员(app)")
    @PostMapping("/removeUserToTempTeam")
    @Login
    public R removeUserToTempTeam(@ApiIgnore @LoginUser SysUserEntity user, @RequestBody Integer userId) {
        if (null == userId) {
            throw new RRException("参数有误");
        }
        sysUserService.removeUserToTempTeam(user, userId);
        return R.ok();
    }

    /**
     * 装车组人员切换
     */
    @ApiOperation("装车组人员切换(app)")
    @PostMapping("/shiftZhuangcheUser")
    @Login
    public R shiftZhuangcheUser(@RequestBody Integer userId) {
        if (null == userId) {
            throw new RRException("参数有误");
        }
        //其实就是换下人员区域
        SysUserEntity user = sysUserService.getOne(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getUserId, userId).select(SysUserEntity::getUserId, SysUserEntity::getLoadAreaType));
        if (null == user) {
            throw new RRException("对象不存在");
        }
        int loadAreaType = user.getLoadAreaType().intValue();
        if (1 == loadAreaType) {
            user.setLoadAreaType(2);
        } else {
            user.setLoadAreaType(1);
        }
        sysUserService.updateById(user);
        //然后还要把这个人从当前的岛上踢下来
        islandService.update(new CfgIsland(), new UpdateWrapper<CfgIsland>().set(CfgIsland.USERID, null).eq(CfgIsland.USERID, userId));
        return R.ok();
    }

    /**
     * 根据部门或分组获取用户列表
     */
    @ApiOperation("根据部门或分组获取用户列表(web)")
    @GetMapping("/listByDeptTeam")
    @Login
    public R listByDeptTeam(@RequestParam Map<String, Object> params, @ApiIgnore @LoginUser SysUserEntity user) {
        PageUtils page = sysUserService.listByDeptTeam(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 首页获取各类人的数量
     */
    @ApiOperation("首页获取各类人的数量(web)")
    @GetMapping("/userClassCount")
    @Login
    public R userClassCount() {
        Map<String, Integer> map = sysUserService.userClassCount();
        return R.ok().put(Constant.DATA, map);
    }
}
